/**
 * 数据分页组件
 */
const pagingBehavior = Behavior({
  data: {
    pageIndex: 1,                           //当前页码
    pageLast: false,                        //是否最后一页
    pageDataLoading: false,                 //是否正在加载数据
    pageLoadMoreShow: false,                //是否显示loadmore控件
    pageLoadMoreType: 'loading',            //loadmore控件显示类型
    pageData: [],                           //分页数据
    hasDataStatus: true,                    //是否有数据(显示状态)
  },
  methods: {
    /** 是否可以加载分页数据 */
    canLoadPageData(firstPage) {
      return !(firstPage === false && this.data.pageLast === true)
    },
    /**
     * 加载分页数据
     * @param loadCallback {function(Object):Promise<Object>} 分页数据加载回调函数
     * @param requestData {Object} 请求数据
     * @param firstPage {boolean} 是否首页
     * @return {Promise<Object>} 返回Promise对象
     */
    loadPageData(loadCallback, requestData, firstPage) {
      if (!this.canLoadPageData(firstPage)) return Promise.resolve({})

      this.data.pageDataLoading = true
      if (firstPage) {
        this.data.pageIndex = 1
        this.data.pageLast = false
      } else {
        this.data.pageIndex = this.data.pageIndex + 1
      }
      this.setData({pageLoadMoreShow: true, pageLoadMoreType: 'loading', hasDataStatus: true})

      if (!requestData) requestData = {}
      requestData.pageIndex = this.data.pageIndex

      const self = this
      return loadCallback(requestData).then(r => {
        self.data.pageDataLoading = false
        self.data.pageLast = r.data['lastPage']

        let list = []
        if (r.data.rows) list = r.data.rows

        const data = {
          // pageData: firstPage ? list : self.data.pageData.concat(list),
          pageLoadMoreShow: self.data.pageLast,
          pageLoadMoreType: self.data.pageLast === true ? 'end' : 'loading',
          hasDataStatus: self.data.pageData.length > 0 || list.length > 0
        }

        if (firstPage) {
          data['pageData'] = [list]
        } else {
          data[`pageData[${(self.data.pageIndex - 1)}]`] = list
        }
        self.setData(data)

        return list
      }).catch(err => {
        self.data.pageDataLoading = false
        self.data.pageLast = false
        self.setData({pageLoadMoreShow: false})
        return Promise.reject(err)
      }).finally(() => {
        if (firstPage) {
          wx.stopPullDownRefresh()
        }
      })
    }
  }
})

module.exports = pagingBehavior
